﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NumberMultiplications
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] input = {1, 2, 3, 4};
            DoNumberMultiplications(input);

            Console.ReadLine();
        }

        static void DoNumberMultiplications(int[] input)
        {
            int i = 0;
            int len = input.Length;

            //
            // Step 1: print out all the numbers.
            //

            for (i = 0; i < len; i++)
            {
                Console.Write("A{0} = {1} \t", i, input[i]);
            }

            Console.WriteLine();

            //
            // Step 2: calculate the multiplication from front and from end.
            //          fromFront[i] = A0 * A1 * ..... * Ai-1
            //          fromBack[i] = Ai+1 * Ai+2 * ...* An-1
            //          Can also limit the space to use one array only and iterate twice.
            //

            int[] fromFront = new int[len];
            int[] fromBack = new int[len];

            fromFront[0] = 1;

            fromBack[len - 1] = 1;

            for (i = 1; i < len; i++)
            {
                fromFront[i] = fromFront[i - 1] * input[i - 1];
            }

            for (i = len - 2; i >= 0; i--)
            {
                fromBack[i] = fromBack[i + 1] * input[i + 1];
            }

            Console.WriteLine(" ******** Result *******");

            for (i = 0; i < len; i++)
            {
                Console.Write("S{0} =", i);

                for (int j = 0; j < len; j++)
                {
                    if (j != i)
                    {
                        Console.Write((j == 0 || (j == 1 && i == 0)? "" : " * ") + "A{0}", j); 
                    }
                }

                Console.WriteLine(" = {0} ", fromFront[i] * fromBack[i]);
            }
        }
    }
}
